var _=require('lodash');

var initialState={
	lists:[],
    carts:[],
    total:0, 
    productionDetail:{},
    productionType:{},
    productionClassify:{}

}

function product(state=initialState,action){
    switch(action.type){
        case "CALTOTAL"://计算总价
            var countTotal =0;
            for(var i=0;i<state.carts.length;i++){
                countTotal+=parseInt(state.carts[i].unitprice);
            }
            return Object.assign({},state,{total:countTotal})
        case "GETLISTS"://获取产品列表
            return Object.assign({},state,{lists:action.data});
            
        case "ADDTOCART"://添加产品与增加数量（+1）
            var productsAdd =_.findIndex(state.carts,{'_id':action.data._id});
            if(productsAdd === -1){
                action.data.quantity=1;
            }else{
                state.carts[productsAdd].quantity = state.carts[productsAdd].quantity +1;
            };
            return {
                ...state,
                carts:[
                    ...state.carts,
                    action.data
                ]
            }
        case "REDUCENUM"://减少数量1
            var productsRed =_.findIndex(state.carts,{'_id':action.data._id});
            if(state.carts[productsRed].quantity>1){
                state.carts[productsRed].quantity=state.carts[productsRed].quantity -1;
            }else{
                console.info('当前数量1，如不需要，请点击删除按钮')
            };
		return {
			...state,
			carts:[
				...state.carts,
				action.data
			]
        }
        case "GETPRODUCTIONTYPE":
            return Object.assign({},state,{productionType:action.data});
        case "GETPRODUCTIONCLASSIFY":
            return Object.assign({},state,{productionClassify:action.data});
        case "GETPRODUCTIONCDETAIL":
            return Object.assign({},state,{productionDetail:action.data});
        default:
            return state;
    }
}

export default product;